package xyz.lne.researchgroupmanage.security;

import com.google.common.collect.ImmutableMap;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import xyz.lne.researchgroupmanage.exception.PowerException;
import xyz.lne.researchgroupmanage.service.dataTransferObject.JwtUserDTO;
import xyz.lne.researchgroupmanage.util.SecurityUtils;

import java.util.List;
import java.util.stream.Collectors;


/**
 * Designed By Lne.
 * 2021/1/28 13:09
 */
public class UserPower {
   public static final String RESEARCH_GROUP_MANAGE = "rgm:";
   public static final String RESEARCH_GROUP_JOIN = "rgj:";
   public static final String RESEARCH_MANAGE = "rm:";
   public static final String RESEARCH_JOIN = "rj:";
   public static final  String PARTICIPATE_TASK = "pt:";

   public static Integer check(String kind, Integer id){
      UserDetails userDetails = SecurityUtils.getCurrentUser();
      JwtUserDTO jwtUserDTO = (JwtUserDTO) userDetails;
      List<String> powers = userDetails.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
      if (powers.contains(kind+id)) return jwtUserDTO.getUserId();
      if (kind.equalsIgnoreCase(RESEARCH_GROUP_JOIN)&&powers.contains(RESEARCH_GROUP_MANAGE+id)) return jwtUserDTO.getUserId();
      if (kind.equalsIgnoreCase(RESEARCH_JOIN)&&powers.contains(RESEARCH_MANAGE+id)) return jwtUserDTO.getUserId();
      throw new PowerException(ImmutableMap.of("权限不足", kind+id));
   }
}
